import java.util.Comparator;
import java.util.PriorityQueue;
class IntCompare implements Comparator<Integer> {
    @Override
    public int compare(Integer o1, Integer o2) {
        return o2.compareTo(o1) ;
    }
}
public class Solution_0318 {
    //小根堆实现，最大topK问题
    //时间复杂度：O(nlogk)
    public int[] MaxtK(int[] arr, int k) {
        if (k == 0 || arr.length == 0) {
            return new int[0];
        }
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();
        for (int i = 0; i < k; i++) {
            priorityQueue.offer(arr[i]);
        }
        for (int i = k; i < arr.length; i++) {
            if (arr[i] > priorityQueue.peek()) {
                priorityQueue.poll();
                priorityQueue.offer(arr[i]);
            }
        }
        int[] arr2 = new int[k];
        for (int i = 0; i < k; i++) {
            arr2[i] = priorityQueue.poll();
        }
        return arr2;
    }
    // 大根堆实现
    // 时间复杂度：O(nlogk)
    public int[] smallestK(int[] arr, int k) {
        if (k == 0 || arr.length == 0) {
            return new int[0];
        }
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(new IntCompare());
        for (int i = 0; i < k; i++) {
            priorityQueue.offer(arr[i]);
        }
        for (int i = k; i < arr.length; i++) {
            if (arr[i] < priorityQueue.peek()) {
                priorityQueue.poll();
                priorityQueue.offer(arr[i]);
            }
        }
        int[] arr2 = new int[k];
        for (int i = 0; i < k; i++) {
            arr2[i] = priorityQueue.poll();
        }
        return arr2;
    }

    // 小根堆实现
    // 时间复杂度：O(nlogk)
    public int[] smallestK1(int[] arr, int k) {
        if (k == 0 || arr.length == 0) {
            return new int[0];
        }
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        for (int i = 0; i < arr.length; i++) {
            pq.offer(arr[i]);
        }
        int[] res = new int[k];
        for (int i = 0; i < k; i++) {
            res[i] = pq.poll();
        }
        return res;
    }
}

